# -*- coding: utf-8 -*-

#    OriginDB
#    Copyright (C) 2009  Jason Power <power.jg@gmail.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from PyQt4 import QtCore, QtGui
from ui_referenceEdit import Ui_ReferenceEditFrame
from MySQLdb import OperationalError

class ReferenceEdit(QtGui.QFrame):
	def __init__(self, controller, referenceClass, mode='New'):
		QtGui.QFrame.__init__(self)

		self.controller = controller

		self.referenceClass = referenceClass
		self.reference = None

        # Set up the user interface from Designer.
		self.ui = Ui_ReferenceEditFrame()
		self.ui.setupUi(self)

		self.setMode(mode)

		self.setReadonly(not self.controller.userLoggedIn())

		self.connect(self.ui.addPushButton, QtCore.SIGNAL("clicked()"), self.insertReference)
		self.connect(self.ui.updatePushButton, QtCore.SIGNAL("clicked()"), self.updateReferenceAction)
		self.connect(self.ui.searchPushButton, QtCore.SIGNAL("clicked()"), self.search)


	def insertReference(self):
		self.reference = self.referenceClass()

		self.reference.insert()

		self.updateReference()

		if self.mode.find("Dialog") != -1:
			self.controller.addToReaction(self.reference, "Reference")

		self.msgDialog = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Reference Added", "Reference added successfully", QtGui.QMessageBox.Ok)
		self.msgDialog.show()


	def updateReference(self):

		self.reference.title = str(self.ui.nameLineEdit.text()).strip()
		self.reference.year = self.ui.yearSpinBox.value()
		if self.reference.year == 1800:
			self.reference.year = None
		self.reference.author_name = self.ui.authorLineEdit.text()
		self.reference.source = str(self.ui.journalLineEdit.text()).upper().strip()
		self.reference.volume = self.ui.volumeSpinBox.value()
		self.reference.issue = self.ui.issueSpinBox.value()
		self.reference.pageStart = self.ui.pageStartSpinBox.value()
		self.reference.pageEnd = self.ui.pageEndSpinBox.value()
		self.reference.abstract = self.ui.abstractTextEdit.toPlainText()

	def updateReferenceAction(self):
		self.updateReference()

		self.msgDialog = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Reference Updated", "Reference updated successfully", QtGui.QMessageBox.Ok)
		self.msgDialog.show()

	def search(self):
		self.reference = self.referenceClass()
		self.updateReference()

		if self.mode.find("Dialog") == -1:
			self.controller.searchReference(self.reference)
		else:
			self.controller.searchReferenceFromDialog(self.reference)


	def clear(self):
		self.ui.nameLineEdit.clear()
		self.ui.yearSpinBox.setValue(1800)
		self.ui.authorLineEdit.clear()
		self.ui.journalLineEdit.clear()
		self.ui.volumeSpinBox.setValue(1)
		self.ui.issueSpinBox.setValue(0)
		self.ui.pageStartSpinBox.setValue(0)
		self.ui.pageEndSpinBox.setValue(0)
		self.ui.abstractTextEdit.clear()

	def setCurrentReference(self, reference):
		self.reference = reference
		self.updateFields()

	def setReadonly(self, readonly):
		self.readonly = readonly

		#self.ui.nameLineEdit.setReadOnly(readonly)
		#self.ui.yearSpinBox.setReadOnly(readonly)
		#self.ui.authorLineEdit.setReadOnly(readonly)
		#self.ui.journalLineEdit.setReadOnly(readonly)
		#self.ui.volumeSpinBox.setReadOnly(readonly)
		#self.ui.pagesLineEdit.setReadOnly(readonly)

		self.ui.addPushButton.setEnabled(not readonly)
		
		if readonly:
			self.ui.updatePushButton.hide()
		else:
			self.ui.updatePushButton.show()

	def setMode(self, mode):
		self.mode = mode
		if self.mode.find("New") != -1:
			self.ui.addPushButton.show()
			self.ui.updatePushButton.hide()
			self.ui.searchPushButton.hide()
		elif mode == "Search":
			self.ui.addPushButton.hide()
			if self.readonly:
				self.ui.updatePushButton.hide()
			else:
				self.ui.updatePushButton.show()
			self.ui.searchPushButton.show()
		elif mode == "Search Dialog":
			self.ui.addPushButton.hide()
			self.ui.updatePushButton.hide()
			self.ui.searchPushButton.show()

	def updateFields(self):
		self.ui.nameLineEdit.setText(self.reference.title)
		self.ui.yearSpinBox.setValue(int(self.reference.year))
		self.ui.authorLineEdit.setText(self.reference.author_name)
		self.ui.journalLineEdit.setText(self.reference.source)
		self.ui.volumeSpinBox.setValue(int(self.reference.volume))
		self.ui.issueSpinBox.setValue(int(self.reference.issue))
		self.ui.pageStartSpinBox.setValue(int(self.reference.pageStart))
		self.ui.pageEndSpinBox.setValue(int(self.reference.pageEnd))
		self.ui.abstractTextEdit.setPlainText(self.reference.abstract)

	def importReference(self):
		dialog = QtGui.QFileDialog(self, "Choose file to import", "", "")
		dialog.setAcceptMode(QtGui.QFileDialog.AcceptOpen)
		dialog.setFileMode(QtGui.QFileDialog.ExistingFile)
		filename = ''
		if dialog.exec_():
			for name in dialog.selectedFiles():
				filename = name
		if not filename:
			return

		f = file(filename)
		line = f.next()
		if line.strip() != "FN ISI Export Format":
			dialog = QtGui.QMessageBox(QtGui.QMessageBox.Critical, "File Error", "File is not of the right type.\n Please only import text files from ISI", QtGui.QMessageBox.Ok)
			dialog.setModal(True)
			dialog.exec_()

		self.reference = self.referenceClass()

		working = None
		for line in f:
			if line[0:2] != "  ":
				working = None
			if line[0:2] == "AU":
				working = "self.reference.author_name"
			elif line[0:2] == "AF":
				self.reference.author_name = ""
				working = "self.reference.author_name"
			elif line[0:2] == "TI":
				working = "self.reference.title"
			elif line[0:2] == "SO":
				working = "self.reference.source"
			elif line[0:2] == "AB":
				working = "self.reference.abstract"
			elif line[0:2] == "PY":
				self.reference.year = int(line[3:])
			elif line[0:2] == "VL":
				self.reference.volume = int(line[3:])
			elif line[0:2] == "IS":
				self.reference.issue = int(line[3:])
			elif line[0:2] == "BP":
				self.reference.pageStart = int(line[3:])
			elif line[0:2] == "EP":
				if line.find('&') != -1:
					self.reference.pageEnd = 0
				else:
					self.reference.pageEnd = int(line[3:])
			elif line[0:2] == "ER":
				break

			if working:
				exec(working + " += line[3:-1]+' '")
				if working == "self.reference.author_name":
					self.reference.author_name += "; "

		print self.reference.author_name
		print self.reference.title
		print self.reference.source
		print self.reference.abstract
		print self.reference.year
		print self.reference.volume
		print self.reference.issue
		print self.reference.pageStart
		print self.reference.pageEnd

		self.updateFields()